import { exportToExcel } from '@/components/ExportToExcel';
import { addLogs } from '@/services/api/log';
import {
  addSupplier,
  deleteSupplier,
  getSupplierList,
  updateSupplier,
} from '@/services/api/supplier';
import { DownloadOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  ModalForm,
  PageContainer,
  ProColumns,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { useAccess, useRouteProps } from '@umijs/max';
import { Button, Form, Popconfirm, Space } from 'antd';
import React, { useRef, useState } from 'react';

const Supplier: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [list, setList] = useState<any[]>([]);
  const access = useAccess();

  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [currentId, setCurrentId] = useState<number | undefined>();
  const [selectData, setSelectData] = useState<any[]>([]);
  const [selectKeys, setSelectKeys] = useState<any[]>([]);
  const router = useRouteProps();
  const columns: ProColumns[] = [
    {
      title: '供应商名称',
      key: 'name',
      dataIndex: 'name',
      copyable: true,
    },
    {
      title: '供应商联系人',
      key: 'contact',
      dataIndex: 'contact',
      copyable: true,
    },
    {
      title: '手机号',
      key: 'phone',
      dataIndex: 'phone',
      copyable: true,
      // hideInSearch: true,
    },
    {
      title: '供应商地址',
      key: 'address',
      dataIndex: 'address',
      copyable: true,
      hideInSearch: true,
    },
    {
      title: '出货时间（天）',
      key: 'deliver_time',
      dataIndex: 'deliver_time',
      hideInSearch: true,
    },
    {
      title: '备注',
      key: 'remark',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      key: 'option',
      render: (_, record: any) => {
        return (
          <Space>
            <a
              key="edit"
              onClick={() => {
                handleUpdateModalOpen(true);
                form.setFieldsValue({
                  ...record,
                });
                setCurrentId(record.id);
              }}
            >
              修改
            </a>
            <Popconfirm
              key="delete"
              title="删除"
              description="确定要删除该供应商吗?"
              onConfirm={async () => {
                const success = await deleteSupplier(record.id);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              }}
              // onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <a style={{ color: 'red' }}>删除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  const fnAddLog = async () => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '');

    const obj = {
      user_by_id: userInfo.id,
      type: 'export',
      operate: router.path.split('/')[1],
      operate_name: router.name + '表',
      user_by: userInfo.nickname,
    };
    const res = await addLogs(obj);
    if (res) {
      actionRef.current?.reload();
    }
  };

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        pagination={{
          showSizeChanger: true,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
              form.resetFields();
            }}
          >
            <PlusOutlined /> 新增
          </Button>,
          access.canAdmin ? (
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                const info = selectData.length ? selectData : list;
                exportToExcel(columns, info, router.name);
                fnAddLog();
              }}
            >
              <DownloadOutlined /> 导出
            </Button>
          ) : null,
        ]}
        request={async (param) => {
          setSelectData([]);
          setSelectKeys([]);
          const data = await getSupplierList(param);
          setList(data.data);
          return data;
        }}
        columns={columns}
        rowSelection={{
          onChange: (key, data) => {
            setSelectData(data);
            setSelectKeys(key);
          },
          selectedRowKeys: selectKeys,
          fixed: 'left',
        }}
        tableAlertRender={({ selectedRowKeys }) => {
          return (
            <Space size={24}>
              <span>已选 {selectedRowKeys.length} 项</span>
            </Space>
          );
        }}
      />
      <ModalForm
        title={'新增供应商'}
        modalProps={{
          destroyOnClose: true,
        }}
        form={form}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          if (!value.phone) {
            delete value.phone;
          }
          const success = await addSupplier(value);
          if (success?.code === 200) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="供应商名称"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="name"
        />

        <ProFormText
          label="供应商联系人"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="contact"
        />

        <ProFormText
          label="手机号"
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="phone"
        />

        <ProFormTextArea
          label="收货地址"
          fieldProps={{
            maxLength: 200,
          }}
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="address"
        />

        <ProFormText
          label="出货时间"
          placeholder={'10天(精确) 或者 10-20天(范围)'}
          rules={[
            {
              required: false,
              message: '10天(精确) 或者 10-20天(范围)',
            },
          ]}
          style={{ width: '100%' }}
          fieldProps={{
            suffix: '天',
          }}
          name="deliver_time"
        />
        <ProFormTextArea
          label="备注"
          fieldProps={{
            maxLength: 200,
          }}
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="remark"
        />
      </ModalForm>

      <ModalForm
        title={'修改供应商'}
        modalProps={{
          destroyOnClose: true,
        }}
        form={form}
        open={updateModalOpen}
        onOpenChange={handleUpdateModalOpen}
        onFinish={async (value) => {
          if (!value.phone) {
            delete value.phone;
          }
          const success = await updateSupplier({ ...value, id: currentId });
          if (success?.code === 200) {
            handleUpdateModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="供应商名称"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="name"
        />

        <ProFormText
          label="供应商联系人"
          rules={[
            {
              required: true,
              message: '请输入',
            },
          ]}
          name="contact"
        />

        <ProFormText
          label="手机号"
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="phone"
        />

        <ProFormTextArea
          label="收货地址"
          fieldProps={{
            maxLength: 200,
          }}
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="address"
        />
        <ProFormText
          label="出货时间"
          placeholder={'10天(精确) 或者 10-20天(范围)'}
          rules={[
            {
              required: false,
              message: '10天(精确) 或者 10-20天(范围)',
            },
          ]}
          style={{ width: '100%' }}
          fieldProps={{
            suffix: '天',
          }}
          name="deliver_time"
        />
        <ProFormTextArea
          label="备注"
          fieldProps={{
            maxLength: 200,
          }}
          rules={[
            {
              required: false,
              message: '请输入',
            },
          ]}
          name="remark"
        />
      </ModalForm>
    </PageContainer>
  );
};

export default Supplier;
